package com.zkthink.ceres.common.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.StrUtil;
import com.zkthink.exception.BizException;
import com.zkthink.ceres.common.service.SerialService;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Service;

/**
 * Created by kellen on 2020/5/10.流水号生成redis实现
 */
@Service
@Slf4j
public class RedisSerialServiceImpl implements SerialService {

  @Autowired
  private RedisConnectionFactory j2CahceRedisConnectionFactory;

  public static final String SERIAL_KEY = "SERIAL:NUMBER";


  @Override
  public String next(String prefix, int len) {
    if (len < 15) {
      throw new BizException("入参错误");
    }
    RedisAtomicLong redisAtomicLong = new RedisAtomicLong(SERIAL_KEY,
        j2CahceRedisConnectionFactory);
    String dateStr = LocalDateTime.now()
        .format(DateTimeFormatter.ofPattern(DatePattern.PURE_DATETIME_PATTERN));
    len = len - dateStr.length();
    redisAtomicLong.expire(60, TimeUnit.SECONDS);
    String serial = String.valueOf(redisAtomicLong.incrementAndGet());
    if (serial.length() > len) {
      redisAtomicLong = new RedisAtomicLong(SERIAL_KEY, j2CahceRedisConnectionFactory, 1);
      serial = String.valueOf(redisAtomicLong.incrementAndGet());
    }
    return prefix + dateStr + StrUtil.fillBefore(serial, '0', len);
  }
}
